use regex::Regex;

pub fn convert_base(num_str: &str, to_base: u32) -> String {
    // 思路：正则表达式解析字符串，并向目标进制转换
    let re = Regex::new(r"^([0-9a-zA-Z]+)\((\d+)\)$").unwrap();
    if let Some(captures) = re.captures(num_str) {
        let origin_value = &captures[1];
        let from_base = captures[2].parse().unwrap();
        match u32::from_str_radix(origin_value, from_base) {
            Ok(mut value) => {
                let mut ans = String::new();
                while value > 0 {
                    let digit = (value % to_base) as u8;
                    let digit_ch = match digit {
                        0..=9 => (digit + b'0') as char,
                        10..=35 => (digit + b'a' - 10) as char,
                        _ => unreachable!(),
                    };
                    ans.push(digit_ch);
                    value /= to_base;
                }
                ans.chars().rev().collect()
            }
            Err(_) => {
                println!("Invalid input value");
                String::new()
            }
        }
    } else {
        println!("Invalid input format");
        String::new()
    }
}
